package com.rem.chat.websocket.netty;

import com.rem.chat.common.utils.RedisComponent;
import com.rem.chat.service.dto.UserLoginDTO;
import com.rem.chat.websocket.ChannelContextUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author: Themberfue
 * @date: 2025/6/12 19:39
 * @description:
 */
@Component
@ChannelHandler.Sharable
public class HandlerWebSocket extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static final Logger log = LoggerFactory.getLogger(HandlerWebSocket.class);

    @Resource
    RedisComponent redisComponent;

    @Resource
    ChannelContextUtil channelContextUtil;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("有新的连接加入...");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("有连接断开...");
        channelContextUtil.removeContext(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        Channel channel = ctx.channel();
        Attribute<String> attribute = channel.attr(AttributeKey.valueOf(channel.id().toString()));
        String userId = attribute.get();
        log.info("收到来自用户id：{} 的消息：{}", userId, textWebSocketFrame.text());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete complete) {
            String uri = complete.requestUri();
            String token = getToken(uri);
            if (null == token) {
                ctx.channel().close();
                return;
            }

            UserLoginDTO userInfo = redisComponent.getUserInfoByToken(token);
            if (null == userInfo) {
                log.info("鉴权失败，token错误：{}", token);
                ctx.channel().close();
                return;
            }
            log.info("通过鉴权：{}", userInfo);
            channelContextUtil.addContext(userInfo.getUserId(), ctx.channel());
            redisComponent.saveUserHeartBeat(userInfo.getUserId());
        }
    }

    private String getToken(String uri) {
        if (!StringUtils.hasLength(uri) || !uri.contains("?")) {
            return null;
        }

        String[] params = uri.split("\\?");
        if (params[1] == null) {
            return null;
        }

        String[] token = params[1].split("=");
        if (token[1] == null) {
            return null;
        }
        return token[1];
    }
}
